<?php
/**
 * This file is part of workerman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link http://www.workerman.net/
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
 */

/**
 * 用于检测业务代码死循环或者长时间阻塞等问题
 * 如果发现业务卡死，可以将下面declare打开（去掉//注释），并执行php start.php reload
 * 然后观察一段时间workerman.log看是否有process_timeout异常
 */
//declare(ticks=1);

use \GatewayWorker\Lib\Gateway;
use \GatewayWorker\Lib\Db;
require_once __DIR__ . '/../../vendor/workerman/gateway-worker/src/Connection.php';
// $db = Db::instance('come');

/**
 * 主逻辑
 * 主要是处理 onConnect onMessage onClose 三个方法
 * onConnect 和 onClose 如果不需要可以不用实现并删除
 */
class Events
{
    public static $db = null;

    /**
     * 进程启动后初始化数据库连接
     */
    public static function onWorkerStart($worker)
    {
        self::$db = new \Workerman\MySQL\Connection('127.0.0.1', '3306', 'coman', 'coman_2019', 'display');
    }


    /**
     * 当客户端连接时触发
     * 如果业务不需此回调可以删除onConnect
     * 
     * @param int $client_id 连接id
     */
    public static function onConnect($client_id)
    {
        // 向当前client_id发送数据 
        // $data['error'] = 10000; 
        // $data['msg'] = "登陆成功"; 
        // $data['data'] = $client_id;
        // Gateway::sendToClient($client_id, json_encode($data, true)); 

        // 向所有人发送
        //Gateway::sendToAll("$client_id login\r\n");
    }
    
   /**
    * 当客户端发来消息时触发
    * @param int $client_id 连接id
    * @param mixed $message 具体消息
    */
   public static function onMessage($client_id, $message)
   {

        // 使用数据库实例
        $data['error'] = 10002; 
        $data['msg'] = "网络异常"; 
        $req_data = json_decode($message, true);
        if(!empty($req_data['userid']) && !empty($req_data['sen_type'])){
            $uid = $req_data['userid'];   
			$type = $req_data['sen_type'];
            if(!Gateway::isUidOnline($uid))
            {
                Gateway::bindUid($client_id, $uid);
            }
			switch ($type)
			{
			case 'send_msg':
			if(empty($req_data['yid'])) 
                return Gateway::sendToClient($client_id, json_encode(['error'=>10002,'msg'=>'不合法的参数'], true)); 
            $yid = $req_data['yid'];
            if(!Gateway::isUidOnline($yid) || !$_clientId = Gateway::getClientIdByUid($yid)[0])
                return Gateway::sendToClient($client_id, json_encode(['error'=>10002,'msg'=>'用户已离线'], true)); 
                Gateway::sendToClient($client_id, json_encode(['error'=>10002,'msg'=>'数据发送成功'], true));
				return Gateway::sendToClient($_clientId, json_encode(['error'=>10001,'msg'=>'更改配置'], true)); 
			break;  
			case 'send_login':
			$proty = $req_data['pro_type'];
            $data['error'] = 10003;
            $_SESSION['web_type'] = $proty;
            $_SESSION['web_uid'] = $uid;
			if($proty == 'spatv'){
                    //更新在线状态
                    if(self::$db->select('*')->from('play_movie_hister')->where("equipmentid= '{$uid}' ")->where("sex= 1 ")->row() || $re = self::$db->update('play_movie_hister')->cols(array('sex'=>1))->where("equipmentid= '{$uid}' ")->query())
                    $data['msg'] = "水疗设备已上线";
                }elseif($proty == 'print'){
                    if(self::$db->select('*')->from('play_print')->where("print_id= '{$uid}' ")->where("sex= 1 ")->row() || $re = self::$db->update('play_print')->cols(array('sex'=>1))->where("print_id= '{$uid}' ")->query())
                    $data['msg'] = "打印设备已就绪";
                }elseif($proty == 'root'){
                    if($re = self::$db->update('play_admin')->cols(array('sex'=>1))->where("username= '{$uid}' ")->query())
                    $data['msg'] = "更新状态成功";
                }else{
                    // 如果传递的消息不ok就踢掉对应客户端
                    return Gateway::closeClient($client_id);
				}
				break;
                case 'send_order':
                    //验证设备
                    if(!$re = self::$db->select('*')->from('play_movie_hister')->where("equipmentid= '{$uid}' ")->row())
                        return Gateway::sendToClient($client_id, json_encode(['error'=>10002,'msg'=>'设备状态异常'], true)); 
                    if(empty($req_data['message']) || !$req_data['message'] || $req_data['message'] == '' || !is_array($req_data['message'])) return Gateway::sendToClient($client_id, json_encode(['error'=>10002,'msg'=>'参数错误'], true));
                        //$cont = json_decode($req_data['message'], true);
                        // 插入
						$total = 0;
						$time=time();
						$cont = array();
						$soce = $time.'(❤ ω ❤)pinxun'.rand(100,999);
                        $ord_id = substr($soce,0,26);
                        $rest = $req_data['message'];
						//$rest = json_decode($req_data['message'],true);
						foreach($rest as $v=>$k){
							$result = self::$db->select('*')->from('play_consumer')->where("id={$k['id']}")->row();
							if(!$result || $result['num']*1<$k['num']*1 || !self::$db->update('play_consumer')->cols(array('num'=>$result['num']*1-$k['num']*1))->where("id= {$k['id']} ")->query()) {
								$data['msg'] = "商品信息不可用";
								return Gateway::sendToClient($client_id, json_encode(['error'=>10002,'msg'=>'商品信息不可用'], true)); 
							}
							$cont[$v]['id'] = $result['id'];
							$cont[$v]['num'] = $k['num'];
							$cont[$v]['name'] = $result['name'];
							$cont[$v]['amount'] = $result['price'];
							$total += $result['price']*1*$k['num']*1;
						}
						$arry = array('order_id'=>$ord_id,'order_total'=>$total,'order_time'=>$time,'order_source'=>$uid,'order_sture'=>0,'order_content'=>json_encode($cont));
                        if(!$re = self::$db->insert('play_order')->cols($arry)->query()) 
                        return Gateway::sendToClient($client_id, json_encode(['error'=>10002,'msg'=>'订单创建失败'], true));
                        if(!$print = self::$db->select('*')->from('play_print')->where("sex= 1 ")->where("sture= 1 ")->row())
                        return Gateway::sendToClient($client_id, json_encode(['error'=>10002,'msg'=>'打印设备已离线'], true));
                        $qid = $print['print_id'];
                        if(!Gateway::isUidOnline($qid) || !$_clientId = Gateway::getClientIdByUid($qid)[0])
                        return Gateway::sendToClient($client_id, json_encode(['error'=>10002,'msg'=>'打印设备已离线'], true));
                        Gateway::sendToClient($client_id, json_encode(['error'=>10001,'msg'=>'发送打印数据成功'], true));
						$arr = array('order_id'=>$ord_id,'order_total'=>$total,'order_time'=>$time,'order_source'=>$uid,'order_sture'=>0,'order_content'=>$cont);
                        return Gateway::sendToClient($_clientId, json_encode(['error'=>10001,'msg'=>'打印订单','data'=>$arr], true));
				break;
                case 'send_agin':
				if(!$print = self::$db->select('*')->from('play_print')->where("sex= 1 ")->where("sture= 1 ")->row())
                return Gateway::sendToClient($client_id, json_encode(['error'=>10002,'msg'=>'打印设备未就绪'], true));
                $qid = $print['print_id'];
                if(!Gateway::isUidOnline($qid) || !$_clientId = Gateway::getClientIdByUid($qid)[0])
                return Gateway::sendToClient($client_id, json_encode(['error'=>10002,'msg'=>'打印设备已离线'], true));
                Gateway::sendToClient($client_id, json_encode(['error'=>10001,'msg'=>'发送打印数据成功'], true));
                $arr = $req_data['message'];
                //if(!empty($arr['order_content'])) $arr['order_content'] = json_encode($arr['order_content']);
                return Gateway::sendToClient($_clientId, json_encode(['error'=>10001,'msg'=>'打印订单','data'=>$arr], true));
				break;
				case 'send_beat':
				if($proty == 12){
                   $data['msg']="兑换设备在线";
                }elseif($type == 11){
                   $data['msg']="游戏设备在线";
                }
				break;
				case 'order_back':
				$sture = $req_data['order_sture']?$req_data['order_sture']:0;
				$oid = $req_data['order_id'];
				if($re = self::$db->update('play_order')->cols(array('order_sture'=>$sture))->where("order_id= '{$oid}' ")->query()) return Gateway::sendToClient($client_id, json_encode(['error'=>10001,'msg'=>'更新订单状态成功'], true)); 
				break;
				default:
				//return Gateway::sendToClient($client_id, var_export($data, true));  
				return Gateway::sendToClient($client_id, json_encode($data, true)); 
            }
        }else{
                //$data['msg'] = "不合法的参数"; 
				// 如果传递的消息不ok就踢掉对应客户端
				return Gateway::closeClient($client_id);
        }
		return Gateway::sendToClient($client_id, json_encode($data, true)); 
   }
   
   /**
    * 当用户断开连接时触发
    * @param int $client_id 连接id
    */
   public static function onClose($client_id)
   {
       $data['error'] = 10003;
	   //操作数据库，离线状态
       $data['msg'] = "访客".$client_id."已离线";
       if($_SESSION['web_type'] && $_SESSION['web_uid']){
        $data['error'] = 10003;
        $uid = $_SESSION['web_uid'];
        switch($_SESSION['web_type']){
                case 'spatv':
                if($re = self::$db->update('play_movie_hister')->cols(array('sex'=>0))->where("equipmentid = '{$uid}'")->query())
                    $data['msg'] = "水疗电视设备".$uid."已离线，可前往控制台查看";
                break;
                case 'print':
                    if($re = self::$db->update('play_print')->cols(array('sex'=>0))->where("print_id = '{$uid}'")->query())
                    $data['msg'] = "游戏设备".$uid."已离线，可前往控制台查看";
                break;
                case 'root':
                    if(self::$db->update('play_admin')->cols(array('sex'=>0))->where("username = '{$uid}'")->query())
                    $data['msg'] = "用户".$uid."已离线";
                break;
                default:
            }
       }
	    try
        {
            if($re = self::$db->select('username')->from('play_admin')->where("sex=1")->row()){
                $qid = $re['username'];
                //如果当前用户在线，发送给当前用户
                if(Gateway::isUidOnline($qid) && $_clientId = Gateway::getClientIdByUid($qid)[0]){
                    return GateWay::sendToClient($_clientId, json_encode($data, true));
                }
            }
        }
        catch (Exception $ex)
        { 
            print_r($ex->getTraceAsString());
        }
   }

   private function _issConsumer($id,$num,$table='play_consumer')
   {
	   if(!$re = self::$db->select('*')->from($table)->where("id= {$id} ")->row()) return false;
		if($re['num']*1<$num*1) return false;
		if(!self::$db->update($table)->cols(array('num'=>$re['num']*1-$num*1))->where("id= {$id} ")->query()) return false;
		return $re;
   }
}
